<template>
  <configure-panel
    :form="enhancedForm"
    :options="enhancedOptions"
    :collapse="collapse"
    @onCloseItemEventClick="e => $emit('onCloseItemEventClick', e)"
    @onClearEventClick="e => $emit('onClearEventClick', e)"
    @onFormItemChange="onFormItemChange"
  />
</template>

<script>
import ConfirgurePanel from "@stack/configure-panel/index.vue";

export default {
  data() {
    return {
      enhancedForm: {},
      enhancedOptions: {},
    }
  },
  watch: {
    compose: {
      immediate: true,
      handler({ form, options, actions }) {
        this.enhancedForm = {
          ...form,
          event: {},
        }
        this.enhancedOptions = {
          ...options,
          event: this.getEventOptions(actions)
        }
      }
    }
  },
  props: {
    form: {
      type: Object,
      default: () => ({}),
    },
    options: {
      type: Object,
      default: () => ({}),
    },
    collapse: {
      type: Object,
      default: () => ({}),
    },
    eventHubConfig: {
      type: Object,
      default: () => ({}),
    },
    actions: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    'configure-panel': ConfirgurePanel,
  },
  computed: {
    compose() {
      const { form, options, actions } = this
      return { form, options, actions }
    }
  },
  methods: {
     getEventOptions(actions) {
       return [
        {
          type: "tags",
          label: "已绑定",
          formKey: "confirmed-events",
          options: actions,
        },
        {
          type: "select",
          label: "触发方式",
          formKey: "emitType",
          config: {
            placeholder: "请选择",
            showAllLevels: false,
            options: this.eventHubConfig.eventEmitTypes,
          }
        },
        {
          type: "multiSelect",
          label: "触发动作",
          formKey: "type",
          config: {
            placeholder: "请选择",
            showAllLevels: false,
            options: this.eventHubConfig.eventTypes,
          }
        },
      ]
    },
    getResolvedValue(value) {
      return Array.isArray(value) ? this.eventHubConfig.concatEventName(...value) : value;
    },
    getExtendsTypeOptions(resolvedValue) {
      return (
        (this.eventHubConfig.eventForms.find((item) => item.type === resolvedValue) || {}).forms ||
        []
      );
    },
    getDefaultEventOptions(scope) {
      return this.enhancedOptions[scope].filter(
        ({ formKey }) => formKey === "confirmed-events" || formKey === "emitType" || formKey === "type"
      );
    },
    getExtendsTypeOptionsValue() {
      const form = JSON.parse(JSON.stringify(this.enhancedForm.event));
      const result = {}
      Object.keys(form).forEach(key => {
        if (key === 'type' || key === 'emitType') return;
        
        const { eventForms, concatEventName } = this.eventHubConfig
        const { forms } = eventForms.find(item => item.type === concatEventName(...form.type))
        const formItem = forms.find(form => form.formKey === key)
        if (formItem && formItem.type === 'cascader') {
          form[key] = form[key].join('')
        }
        result[key] = form[key]
      })
      return result;
    },
    getEventButtonOptions() {
      const get = (type) => this.getResolvedValue(this.enhancedForm.event[type]);
      return {
        // dxz
        type: "custom-button",
        buttonText: "添加事件",
        buttonStyle: { width: "100%" },
        onClick: (event) => {
          // TODO: 「验证是否添加事件成功」
          // TODO: 添加 「已添加的事件」「支持点击-编辑事件」
          const type = get("type");
          const emitType = get("emitType");
          const params = this.buildEventParams(emitType, type);
          console.log("params", params);
      // this.enhancedForm= {}
      // this.enhancedOptions= {}
          this.$emit('onAppendEvent', params)
        },
      };
    },
    generateEventId() {
      return Math.random().toString(36).slice(3, 9);
    },
    buildEventParams(emitType, type, id) {
      const isApi = false;
      const res = {
        id: id || this.generateEventId(),
        emitBy: emitType,
        type: type,
      };
      if (isApi) {
        const { teamInfo } = store.state;
        res.params = {
          url: `/api/dynamic/${method}-data`,
          params: {
            ...this.getExtendsTypeOptionsValue(),
            teamId: teamInfo.id,
          },
        };
      } else {
        res.params = this.getExtendsTypeOptionsValue();
      }

      return res;
    },
    onFormItemChange(scope, { key, value, item }) {
      console.log(scope, { key, value, item })
      if (scope === 'event') {
        const resolvedValue = this.getResolvedValue(value);
        this.enhancedForm[scope][key] = value;
        if (key === "type") {
          this.enhancedOptions[scope] = this.getDefaultEventOptions(scope)
            .concat(this.getExtendsTypeOptions(resolvedValue))
            .concat(this.getEventButtonOptions());
        }
        if (key === 'confirmed-events') {
          const deleteAction = Boolean(!value)
          if (deleteAction) {
            return this.$emit('onCloseItemEventClick', item)
          }
        }
      }
      this.$emit('onFormItemChange', scope, { key, value, item })
    }
  },
}
</script>